package com.qen.fx.tools;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.regex.Pattern;
import java.util.UUID;

public class UUIDValidator {

    private static final Pattern UUID_PATTERN = Pattern.compile(
            "^[0-9a-f]{8}-" +     // 32个十六进制字符，分成5段
                    "[0-9a-f]{4}-" +
                    "[0-9a-f]{4}-" +
                    "[0-9a-f]{4}-" +
                    "[0-9a-f]{12}$",      // 大小写不敏感
            Pattern.CASE_INSENSITIVE
    );

    public static boolean isValidUUIDv3(String uuidStr, UUID namespaceUUID, String name) {
        if (!isValidUUIDFormat(uuidStr)) {
            return false;
        }

        UUID uuid = UUID.fromString(uuidStr);
        int version = (int) ((uuid.getMostSignificantBits() >> 12) & 0xF); // 获取版本号
        if (version != 3) {
            return false;
        }

        // 可选：尝试重新生成UUID并比较
        UUID generatedUUID = generateUUIDv3(namespaceUUID, name);
        return uuid.equals(generatedUUID);
    }

    private static boolean isValidUUIDFormat(String uuidStr) {
        return UUID_PATTERN.matcher(uuidStr).matches();
    }

    private static UUID generateUUIDv3(UUID namespace, String name) {
        byte[] hash;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update((namespace.toString() + name).getBytes(StandardCharsets.UTF_8));
            hash = md.digest();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        long mostSigBits = ((long) hash[3] & 0xFF) << 56;
        mostSigBits |= ((long) hash[2] & 0xFF) << 48;
        mostSigBits |= ((long) hash[1] & 0xFF) << 40;
        mostSigBits |= ((long) hash[0] & 0xFF) << 32;
        mostSigBits |= ((long) hash[5] & 0xFF) << 24 | 0x3000000; // 设置版本号为3
        mostSigBits |= ((long) hash[4] & 0xFF) << 16;
        mostSigBits |= ((long) hash[7] & 0x0F) << 12; // 清除变种位
        mostSigBits |= ((long) hash[6] & 0xFF) << 4;

        long leastSigBits = ((long) hash[8] & 0xFF) << 56;
        leastSigBits |= ((long) hash[9] & 0xFF) << 48;
        leastSigBits |= ((long) hash[10] & 0xFF) << 40;
        leastSigBits |= ((long) hash[11] & 0xFF) << 32;
        leastSigBits |= ((long) hash[12] & 0xFF) << 24;
        leastSigBits |= ((long) hash[13] & 0xFF) << 16;
        leastSigBits |= ((long) hash[14] & 0xFF) << 8;
        leastSigBits |= ((long) hash[15] & 0xFF);

        return new UUID(mostSigBits, leastSigBits);
    }

    public static void main(String[] args) {
        UUID dnsNamespace = UUID.fromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
        String name = "example.com";
        String uuidToCheck = "6fa459ea-ee8a-3ca4-894e-db77e1603553"; // 示例UUID

        boolean isValid = isValidUUIDv3(uuidToCheck, dnsNamespace, name);
        System.out.println("The UUID is valid for DNS namespace: " + isValid);
    }
}
